package com.ytf.dogbox.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;

import com.ytf.dogbox.receive.AlarmReciever;

import java.util.Calendar;
import java.util.TimeZone;


/**
 * author:tiwolf
 * create date:2022/3/30
 * Describe:
 */
public class AlarmUtil {



    /**
     *
     * @param context
     * @param time  时间
     * @param num  多一秒
     * @param requestCode 闹钟标记
     */
    public static void alarmPlayer(Context context,String time,int num,int requestCode){
        Calendar startCalendar = getCaledar(time, 1);
        Log.i("TAG", "receiveWork: 广告列表时间戳" + startCalendar.getTimeInMillis());
        Log.i("TAG", "receiveWork: 广告列表小时" + startCalendar.getTime().getHours());
        //未设置过或者已经关掉闹钟的，开始设置闹钟,这个是开的闹钟
        Intent intent1 = new Intent(context, AlarmReciever.class);
        intent1.putExtra("_id", requestCode);
        intent1.putExtra("flag", true);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent1, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//                                            //单次设置
//                                            alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
        //重复设置
//                        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,startCalendar.getTimeInMillis(),(1000 * 60 * 60 * 24),pendingIntent);
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                            //参数2是开始时间、参数3是允许系统延迟的时间
//                            alarmManager.setWindow(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), 1000*5, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟1");
//                        } else {
//                            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), 1000*5, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟2");
//                        }
//                        Log.e(TAG, "receiveWork: 当前获取广告列表00000000");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), pendingIntent);
//                                Log.e(TAG, "receiveWork: 设置了闹钟1");
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), pendingIntent);
//                                Log.e(TAG, "receiveWork: 设置了闹钟2");
        }else {
//                            if (flag == 0) {	//一次性闹钟
//                                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
//                            } else {			//重复闹钟
//                                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.getTimeInMillis()), intervalMillis, sender);
//                            }
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), 60 * 60 * 1000 * 24, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟3");
        }
    }

    /**
     * 进行广播定时
     * @param context
     * @param time
     * @param num
     * @param requestCode
     */
    public static void alarmBroadcast(Context context,String time,int num,int requestCode){
        Calendar startCalendar = getCaledar(time, num);


        Log.i("TAG", "receiveWork: " + startCalendar.getTimeInMillis());
        Log.i("TAG", "receiveWork: " + startCalendar.getTime().getHours());
        //未设置过或者已经关掉闹钟的，开始设置闹钟,这个是开的闹钟
        Intent intent1 = new Intent(context, AlarmReciever.class);
        intent1.putExtra("_id", requestCode);
        intent1.putExtra("flag", true);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent1, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//                                            //单次设置
//                                            alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
        //重复设置
//                        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,startCalendar.getTimeInMillis(),(1000 * 60 * 60 * 24),pendingIntent);
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                            //参数2是开始时间、参数3是允许系统延迟的时间
//                            alarmManager.setWindow(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), 1000*5, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟1");
//                        } else {
//                            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), 1000*5, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟2");
//                        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), pendingIntent);
//                                Log.e(TAG, "receiveWork: 设置了闹钟1");
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), pendingIntent);
//                                Log.e(TAG, "receiveWork: 设置了闹钟2");
        } else {
//                            if (flag == 0) {	//一次性闹钟
//                                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
//                            } else {			//重复闹钟
//                                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.getTimeInMillis()), intervalMillis, sender);
//                            }
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startCalendar.getTimeInMillis(), 60 * 60 * 1000 * 24, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟3");
        }

    }


    /**
     *
     * @param selectTimeStr 这个包含了小时和分钟
     * @param num 这个包含秒的设置，主要用来进行广告无痕衔接
     * @return 获取到的是需要定时的广告时间段
     */
    public static Calendar getCaledar(String selectTimeStr, int num) {
        String[] startStrs = selectTimeStr.split(":");


        //得到日历
        Calendar calendar = Calendar.getInstance();
//                                calendar.setTimeInMillis(System.currentTimeMillis());
        //获取到当前毫秒值
        long systemTime = System.currentTimeMillis();

        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.setTimeZone(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startStrs[0]));
        if (startStrs.length == 2) {
            calendar.set(Calendar.MINUTE, Integer.valueOf(startStrs[1]));
        } else {
            calendar.set(Calendar.MINUTE, 0);
        }
        calendar.set(Calendar.SECOND, num);
        calendar.set(Calendar.MILLISECOND, 0);

        //获取上面设置的时间
        long selectTime = calendar.getTimeInMillis();
        if (systemTime > selectTime) {
            //如果当前时间大于需要设置的时间，因为这个时间是用来定时的。所以添加一天的量来定时第二天的
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        return calendar;
    }


    /**
     *
     * @param selectTimeStr 这个包含了小时和分钟
     * @param num 这个包含秒的设置，主要用来进行广告无痕衔接
     * @return 获取的是当前的广告播放时间段
     */
    public static Calendar getCurrentCaledar(String selectTimeStr, int num) {
        String[] startStrs = selectTimeStr.split(":");


        //得到日历
        Calendar calendar = Calendar.getInstance();
//                                calendar.setTimeInMillis(System.currentTimeMillis());
        //获取到当前毫秒值
        long systemTime = System.currentTimeMillis();

        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.setTimeZone(TimeZone.getDefault());
        calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startStrs[0]));
        if (startStrs.length == 2) {
            calendar.set(Calendar.MINUTE, Integer.valueOf(startStrs[1]));
        } else {
            calendar.set(Calendar.MINUTE, 0);
        }
//        calendar.set(Calendar.MINUTE,Integer.valueOf(startStrs[1]));
        calendar.set(Calendar.SECOND, num);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar;
    }


    /**
     *
     * @param context  上下文
     * @param calendar 日历
     * @param requestCode 闹钟标志
     */
    public static void startAlarm(Context context, Calendar calendar, int requestCode) {
        Intent intent1 = new Intent(context, AlarmReciever.class);
        intent1.putExtra("_id", requestCode);
        intent1.putExtra("flag", true);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent1, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
//                                Log.e(TAG, "receiveWork: 设置了闹钟1");
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
//                                Log.e(TAG, "receiveWork: 设置了闹钟2");
        }else {

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60 * 60 * 1000 * 24, pendingIntent);
//                            Log.e(TAG, "receiveWork: 设置了闹钟3");
        }

    }

    public static void cancelAlarm(int timeIndex,Context context) {
        if (timeIndex == -1) {
            //闹钟没有设置过
        } else {
            //已经设置过，那么需要将之前设置的闹钟，关掉
            Intent intent1 = new Intent(context, AlarmReciever.class);
            intent1.putExtra("_id", timeIndex);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, timeIndex, intent1, 0);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            Log.e("TAG", "cancelAlarm: 直播取消开始闹钟1==" + timeIndex);

        }
    }

    public static void cancelAlarm(int lastStartInt, int lastEndInt,Context context) {
        if (lastStartInt == -1) {
            //闹钟没有设置过
        } else {
            //已经设置过，那么需要将之前设置的闹钟，关掉
            Intent intent1 = new Intent(context, AlarmReciever.class);
            intent1.putExtra("_id", lastStartInt);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, lastStartInt, intent1, 0);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            Log.e("TAG", "cancelAlarm: 直播取消开始闹钟1==" + lastStartInt);

        }

        if (lastEndInt == -1) {
            //闹钟没有设置过
        } else {
            //已经设置过，那么需要将之前设置的闹钟，关掉

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);


            Intent intent2 = new Intent(context, AlarmReciever.class);
            intent2.putExtra("_id", lastEndInt);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, lastEndInt, intent2, 0);
            alarmManager.cancel(pendingIntent);
            Log.e("TAG", "cancelAlarm: 直播取消结束闹钟1==" + lastEndInt);
        }
    }

    /**
     * 设置成整点才会启动播放
     * @param id 返回id
     * @param time 设置的时间
     */
    public static void setNotificationTime(Context context,int id, String time) {
        Calendar calendar = getCaledar(time, 0);
        //未设置过或者已经关掉闹钟的，开始设置闹钟,这个是开的闹钟


        Log.e("TAG", "setNotificationTime: 设置闹铃通知" + id + ",小时：" + calendar.getTime().getHours() +
                ",分钟：" + calendar.getTime().getMinutes() + "===时间戳==" + calendar.getTimeInMillis());
        Intent intent1 = new Intent(context, AlarmReciever.class);
        intent1.putExtra("_id", id);
//        intent1.putExtra("flag",true);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent1, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }else {
//            if (flag == 0) {	//一次性闹钟
//                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
//            } else {			//重复闹钟
//                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.getTimeInMillis()), intervalMillis, sender);
//            }
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }

    }


    /**
     *  搞不同id轮流来定时，看能否解决问题
     * @param id  设置id
     * @param minute 设置延时时间开启
     */
    public static void createRecord(Context context,int id,int minute){
        Calendar calendar=TimeUtil.getCaledar(minute);
        Log.i("TAG", "run: mp4录制-9999,准备定时的时间="+calendar.getTimeInMillis());
//        int id=-100;
        Intent intent1=new Intent(context, AlarmReciever.class);
        intent1.putExtra("_id",id);
        intent1.putExtra("flag",false);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,id,intent1,0);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //大于6.0
            Log.i("TAG", "run: mp4录制-1010,添加的闹钟="+calendar.getTimeInMillis());
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
        } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            //大于4.4
            Log.i("TAG", "run: mp4录制-1212,添加的闹钟");
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pendingIntent);
        } else {
//            if (flag == 0) {	//一次性闹钟
//                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
//            } else {			//重复闹钟
//                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.getTimeInMillis()), intervalMillis, sender);
//            }
            Log.i("TAG", "run: mp4录制-1313,添加的闹钟");
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),  pendingIntent);
        }

    }

    /**
     * 定时一天后相同的时间发生事件
     * @param id 返回id
     */
    public static void set24HourRedo(Context context,int id) {

        Log.i("TAG", "set24HourRedo: 定时器，我正在定时24小时后再发生的事情");
        //未设置过或者已经关掉闹钟的，开始设置闹钟,这个是开的闹钟
        Intent intent1=new Intent(context, AlarmReciever.class);
        intent1.putExtra("_id",id);
        intent1.putExtra("flag",true);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,id,intent1,0);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        // 重复定时任务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+24*60*60*1000, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+24*60*60*1000, pendingIntent);
        }

    }

}
